package order

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

func OrderPay(ctx *gin.Context) { // 订单支付提交
	// 接收参数
	uid := ctx.GetInt("uid")
	orderId := ctx.PostForm("order_id")

	// 校验参数
	if orderId == "" {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 1, "errMsg": "订单ID无效"})
	}

	var newOrderInfo model.OrderInfo
	if ret := global.App.DB.
		Where("order_id = ?", orderId).Where("user_id = ?", uid).
		Where("pay_method = ?", 3).Where("order_status = ?", 1).Find(&newOrderInfo); ret.RowsAffected == 0 {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 2, "errMsg": "订单不存在"})
	}
	global.App.Log.Sugar().Infof("uid: %d, newOrderInfo:%v", uid, newOrderInfo)

	// 计算总金额
	var total_price float64
	total_price = newOrderInfo.TotalPrice.InexactFloat64() + newOrderInfo.TransitPrice.InexactFloat64()

	// 调用支付宝支付接口
	aliPayUrl, err := utils.AliTradePagePay(global.App.Config.AliPay.AppId, global.App.Config.AliPay.AppPrivateKey, global.App.Config.AliPay.AliPublicKey, orderId, total_price)
	if err != nil {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 3, "errMsg": err})
	}

	// 返回支付宝支付界面的url
	ctx.JSON(http.StatusOK, map[string]interface{}{"code": 4, "url": aliPayUrl.String()})
}

func OrderQuery(ctx *gin.Context) { // 订单支付查询
	// 接收参数
	uid := ctx.GetInt("uid")
	orderId := ctx.PostForm("order_id")

	// 校验参数
	if orderId == "" {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 1, "errMsg": "订单ID无效"})
	}

	var newOrderInfo model.OrderInfo
	if ret := global.App.DB.
		Where("order_id = ?", orderId).Where("user_id = ?", uid).
		Where("pay_method = ?", 3).Where("order_status = ?", 1).Find(&newOrderInfo); ret.RowsAffected == 0 {
		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 2, "errMsg": "订单不存在"})
	}

	for {
		ret, err := utils.AliTradeQuery(global.App.Config.AliPay.AppId, global.App.Config.AliPay.AppPrivateKey, global.App.Config.AliPay.AliPublicKey, orderId)
		if err != nil {
			ctx.JSON(http.StatusOK, map[string]interface{}{"code": 3, "errMsg": err})
			return
		}

		if ret.Code == "10000" && ret.TradeStatus == "TRADE_SUCCESS" {
			// 支付成功，获取支付宝返回的支付编号
			trade_no := ret.TradeNo

			// 更新 order_info表
			global.App.DB.Where("order_id = ?", orderId).Updates(&model.OrderInfo{
				OrderStatus: newOrderInfo.OrderStatus + 1,
				TradeNo:     trade_no,
			})

			ctx.JSON(http.StatusOK, map[string]interface{}{"code": 4, "Msg": "支付成功"})
			return
		}

		if ret.Code == "40004" || (ret.Code == "10000" && ret.TradeStatus == "WAIT_BUYER_PAY") {
			// 正在支付状态下，继续循环监听
			time.Sleep(5 * time.Second)
			continue
		}

		ctx.JSON(http.StatusOK, map[string]interface{}{"code": 5, "errMsg": "支付失败"})
		return
	}
}
